import React, { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  NavBar,
  Card,
  List,
  Checkbox,
  Button,
  Modal,
  Form,
  Input,
  Tag,
} from "antd-mobile";
import { SubmitBar } from 'react-vant';
import { useSelector, useDispatch } from "react-redux";
import { UnorderedListOutline, CloseOutline } from "antd-mobile-icons";
import { getXuan, getDel, getAdd, getdit } from "../../store/payname";
import "./index.css";
import request from "../../api/request";
function Index() {
// 调用仓库方法
  const dispatch = useDispatch();
  // 表单
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);
  // 创建redux仓库获取仓库数据
  const { PayList } = useSelector((state) => state.payname);
  const [Editid, setEditid] = useState();
  const [Dispay, setDispay] = useState(false);

  // 点击确定
  const handOk = (item) => {
    // 判断点的是否为确定按钮
    if (item.key === "confirm") {
      // 判断是新增还是修改
      if (Dispay) {
        // 添加数据
        const obj = {
          id: Number(Math.random().toString().slice(2, 6)),
          state: false,
          ...form.getFieldsValue(),
        };
        // 调用仓库方法
        dispatch(getAdd(obj));
      } else {
        // 修改
        const objs = {
          id: Editid,

          ...form.getFieldsValue(),
        };
        // 调用仓库di
        dispatch(getdit(objs));
      }
    }
  };
  const add = () => {
    // 开启弹框
    setVisible(true);
    // 定义状态真值为新增
    setDispay(true);
    // 清空表单
    form.resetFields();
  };
  const edit = (item) => {
    // 开启弹框
    setVisible(true);
    // 定义状态真值为编辑
    setDispay(false);
    // 储存点击的id
    setEditid(item.id);
    // 表单数据回填
    form.setFieldsValue(item);
  };
  const Sao = () => {
    // 获取输入框
    const input = document.createElement("input");
    // 修改输入框属性
    input.type = "file";
    // 输入框默认点击
    input.click();
// 监听输入框
    input.onchange = async () => {
      // 储存数据
      const file = input.files[0];
      const fileData = new FormData();
      fileData.append("file", file);
      // 调用接口
      const res = await request.post("/api/orc/upload/image", fileData);
      console.log(res);
      const { code, data } = res.data;
      if (code === 200) {
        alert("扫描成功");
        // 把扫描数据回填表单
        form.setFieldsValue(data);
      }
    };
  };

// 储存选则
  const Payslist = useMemo(() => {
    return PayList.filter((item) => {
      return item.state;
    });
  }, [PayList]);

  // 判断选择的个数
  const PsonList = useMemo(() => {
  // 根据个数新增作位
    if (Payslist.length === 0) return [];
    if (Payslist.length === 1) {
      return [["A", "B", "C", "D"]];
    }
    if (Payslist.length === 2) {
      return [
        ["A", "B", "C", "D"],
        ["A", "B", "C", "D"],
      ];
    }
    if (Payslist.length === 3) {
      return [
        ["A", "B", "C", "D"],
        ["A", "B", "C", "D"],
        ["A", "B", "C", "D"],
      ];
    }
    if (Payslist.length === 4) {
      return [
        ["A", "B", "C", "D"],
        ["A", "B", "C", "D"],
        ["A", "B", "C", "D"],
        ["A", "B", "C", "D"],
      ];
    }
    if (Payslist.length === 5) {
      return [
        ["A", "B", "C", "D"],
        ["A", "B", "C", "D"],
        ["A", "B", "C", "D"],
        ["A", "B", "C", "D"],
        ["A", "B", "C", "D"],
      ];
    }
  }, [Payslist]);
  // 储存点击的
  const [Pssnlist,setPssnlist]=useState([])

  // 从前往后截取
  const lastList=useMemo(()=>{
       return Pssnlist.slice(-PsonList.length)
  },[Pssnlist,Payslist])

  // 重新把截取的位置赋值
  const appOk=(row,pos)=>{
     setPssnlist([...Pssnlist,{row,pos}])
  }
    const price=Payslist.length*20000
      const Zhidu=()=>{
       navigate(`/orderDel`,{state:price})
  }
  return (
    <div>
      <NavBar onBack={() => navigate(-1)}>填写订单</NavBar>
      <h3>选择乘客</h3>
      <Card title="选择乘车人">
        <Button block color="primary" size="large" onClick={add}>
          新增乘车人
        </Button>
        <List header="操作">
          {PayList.map((item, index) => {
            return (
              <List.Item
                prefix={<UnorderedListOutline onClick={() => edit(item)} />}
                description={
                  <div>
                    <span>{item.code}</span>
                    <span className="sj">{item.sj}</span>
                  </div>
                }
                extra={
                  <div>
                    <span>
                      <CloseOutline onClick={() => dispatch(getDel(item))} />
                    </span>
                    <span>
                      {" "}
                      <Checkbox
                        checked={item.state}
                        onClick={() => dispatch(getXuan(item))}
                      />
                    </span>
                  </div>
                }
                key={index}
              >
                {item.name}
              </List.Item>
            )
          })}
        </List>
      </Card>
      <Modal
        visible={visible}
        content={
          <div>
            {Dispay ? (
              <Button block color="primary" size="large" onClick={() => Sao()}>
                证件扫描
              </Button>
            ) : (
              ""
            )}
            <Form layout="horizontal" form={form}>
              <Form.Header>{Dispay ? "新增乘车人" : "修改乘车人"}</Form.Header>
              <Form.Item
                name="name"
                label="姓名"
                rules={[{ required: true, message: "姓名不能为空" }]}
              >
                <Input placeholder="请输入姓名" />
              </Form.Item>
              <Form.Item
                name="code"
                label="身份证"
                rules={[{ required: true, message: "身份证不能为空" }]}
              >
                <Input placeholder="请输入身份证" />
              </Form.Item>
              <Form.Item
                name="sj"
                label="手机号"
                rules={[{ required: true, message: "手机号不能为空" }]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Form>
          </div>
        }
        closeOnAction
        onClose={() => {
          setVisible(false);
        }}
        onAction={(action) => handOk(action)}
        actions={[
          {
            key: "confirm",
            text: "确定",
          },
          {
            key: "collens",
            text: "取消",
          },
        ]}
      ></Modal>

      {PsonList.map((item, row) => {
        return (
          <div key={row}>
            {item.map((it, pos) => {
              return <Tag style={{margin:10}} color={
                lastList.some((item)=>item.row===row&&item.pos===pos)?'red':'#000'
              } key={pos} onClick={()=>appOk(row,pos)}>{it}</Tag>;
            })}
          </div>
        );
      })}
      <div onClick={()=>Zhidu(price)} className="demo-submit-bar"><SubmitBar price={price} buttonText="提交订单" /></div>
    </div>
  )
}

export default Index;
